package kaufman.id.projects;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;

public class PortScanner {
	private int startPort = 0;
	private int endPort = 65536;
	private String iP = "127.0.0.1";

	public int getStartPort() {
		return startPort;
	}

	public void setStartPort(int startPort) {
		this.startPort = startPort;
	}

	public int getEndPort() {
		return endPort;
	}

	public void setEndPort(int endPort) {
		this.endPort = endPort;
	}

	public String getiP() {
		return iP;
	}

	public void setiP(String iP) {
		this.iP = iP;
	}

	public PortStatus[] getAllPortStatus() {
		PortStatus[] p = new PortStatus[endPort];
		for (int i = 0; i < p.length; i++) {
			PortStatus ps = new PortStatus();
			ps.setPortNumber(i);
			boolean y = isOpen(i);
			ps.setOpen(y);
			p[i] = ps;
		}

		return p;

	}

	private boolean isOpen(int port) {//checks status of ports using socket
		Socket sock = new Socket();
		SocketAddress socka = new InetSocketAddress(iP, port);
		boolean isOpen = true;
		try {
			sock.connect(socka);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			isOpen = false;
		} finally {

			try {
				sock.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				// e.printStackTrace();
			}

		}
		return isOpen;
	}

	public ArrayList<PortStatus> getAllOpenPorts() {
		ArrayList<PortStatus> al= new ArrayList<PortStatus>();
		for (int i = startPort; i < endPort; i++) {
			System.out.println("Checking port" + i);
			PortStatus ps = new PortStatus();
			ps.setPortNumber(i);
			ps.setOpen(isOpen(i));
			if (isOpen(i) == true) {
				al.add(ps);
			}
			
		}
		return al;
	}

}
